package com.polaris.live.utils.livehelper

import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.viewpager2.widget.ViewPager2
import com.polaris.live.adapter.LiveBroadAdapter
import com.polaris.live.common.constant.AppConst
import com.polaris.live.im.sfs.bean.pusher.UserStateMessage
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.back_resp.copyState
import com.polaris.live.utils.zego.LiveActivityIdentifier
import com.polaris.live.utils.zego.LivePlayer

/**
 * 直播滚动帮助类
 *
 * @author Created by lucas on 2023/12/21 14:01
 * @since 1.0.0
 */
class LiveBroadHelper(val viewpage2: ViewPager2, val helperCallBack: HelperCallBack,val owner: LifecycleOwner) {

    private val mAdapter = LiveBroadAdapter(owner)


    init {
        initView()
        initData()
        initObserver()
    }

    private var currentPosition = 0  //选中位置
    private var currentScrollStatePosition = 0 //滑动结束位置
    private var currentLiveStateBean: LiveStateBean? = null

    private var isScrolle = false  //是否在滑动
    private var isTouch = false  //用户是否在操作


    private fun initObserver(){

    }

    private fun initView() {
        mAdapter.setOnItemClickListener { _, view, position ->
            val item =
                mAdapter.getItemOrNull(position)?.displayUserBean ?: return@setOnItemClickListener
            helperCallBack.OnItemClickListener(
                view.findViewById(com.polaris.live.R.id.remoteUserView),
                item
            )
        }
        viewpage2.apply {
            adapter = mAdapter
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                private var lastOffset = 0f
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                    super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                    if (lastOffset == 0f) {
                        lastOffset = positionOffset
                        viewpage2.post {
                            if (lastOffset > 0.5f) { // 向上滑动
                                startUp()
                            } else {   // 向下滑动
                                startDown()
                            }
                        }
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {
                    when (state) {
                        ViewPager2.SCROLL_STATE_IDLE -> {
                            lastOffset = 0f
                            isScrolle = false
                            isTouch = false
                            viewpage2.post {
                                val position = viewpage2.currentItem
                                if (position == currentScrollStatePosition) {  //没有切换
                                    return@post
                                }
                                currentScrollStatePosition = position
                                autoRemovePage()
                            }
                        }

                        ViewPager2.SCROLL_STATE_DRAGGING -> {
                            isScrolle = true
                            isTouch = true
                        }

                        ViewPager2.SCROLL_STATE_SETTLING -> {
                            isTouch = false
                        }
                    }
                }

                override fun onPageSelected(position: Int) {
                    viewpage2.post {
                        if (position == currentPosition) {  //没有切换
                            return@post
                        }
                        currentPosition = position
                        val nowData = mAdapter.getItemOrNull(position)
                        if (nowData !== currentLiveStateBean) { //相等说明是在删除数据
                            startCurrentLive()
                            nowData?.displayUserBean?.base?.userId?.also {
                                helperCallBack.getUserLiveState(it)
                            }
                            autoGetData(mAdapter.data.lastOrNull()?.displayUserBean?.base?.userId)
                            currentLiveStateBean = nowData
                        }
                    }
                }
            })
        }
    }


    private fun startUp() {
        if (mAdapter.getItemOrNull(currentPosition - 1) != null) {
            mAdapter.notifyItemChanged(currentPosition - 1, "notify")
        }
    }

    private fun startDown() {
        if (mAdapter.getItemOrNull(currentPosition + 1) != null) {
            mAdapter.notifyItemChanged(currentPosition + 1, "notify")
        }
    }

    fun startCurrentLive() {
        mAdapter.notifyItemChanged(viewpage2.currentItem, "start")
    }

    fun onResumeLive() {
        if (isEmpty()) {
            autoGetData(null)
        } else {
            mAdapter.data.getOrNull(viewpage2.currentItem)?.displayUserBean?.base?.userId?.let {
                helperCallBack.getUserLiveState(it)
            }
            startCurrentLive()
        }
    }

    /**
     *关闭直播
     */
    fun stopLive() {
        LivePlayer.stopLive(LiveActivityIdentifier.LIVE_BROADCAST_FRAGMENT)
    }

    /**
     *释放资源直播
     */
    fun releaseLive() {
        stopLive()
    }

    private fun initData() {
        mAdapter.addData(LiveStateBean())
        helperCallBack.getFirstData()
    }

    /**
     * 自动删除上面超过阈值的页面和数据
     */
    private fun autoRemovePage() {
        val cPosition = viewpage2.currentItem
        if (cPosition > PREORDERQUANTITY) {
            val count = cPosition - PREORDERQUANTITY
            if (count > 0 && mAdapter.data.size > count) {
                mAdapter.data.subList(0, count).clear() // 删除count个元素
                mAdapter.notifyItemRangeRemoved(0, count)
            }
        }
    }

    fun setData(displayUserBean: DisplayUserBean) {
        mAdapter.data.clear()
        mAdapter.addData(LiveStateBean(displayUserBean, true))
        mAdapter.notifyDataSetChanged()
        autoGetData(displayUserBean.base.userId)
    }

    fun clearData() {
        stopLive()
        mAdapter.data.clear()
        mAdapter.addData(LiveStateBean())
        mAdapter.notifyDataSetChanged()
        autoGetData(null)
    }

    fun updateData(displayUserBean: DisplayUserBean) {
        if (displayUserBean.base.userId == getCurrentUserId()) {
            val data = mAdapter.getItemOrNull(viewpage2.currentItem)
            data?.let { da ->
                val currentDisplayUserBean = da.displayUserBean
                if (currentDisplayUserBean != null) {
                    if (currentDisplayUserBean.base.living != displayUserBean.base.living ||
                        currentDisplayUserBean.base.calling != displayUserBean.base.calling
                    ) {
                        if (displayUserBean.base.living == AppConst.YES && displayUserBean.playStreamId != currentDisplayUserBean.playStreamId) {
                            da.playNow = true
                        }
                        da.displayUserBean = displayUserBean
                        mAdapter.notifyItemChanged(viewpage2.currentItem)
                    } else {
                        if (displayUserBean.base.living == AppConst.YES && displayUserBean.playStreamId != currentDisplayUserBean.playStreamId) {
                            da.playNow = true
                            da.displayUserBean = displayUserBean
                            mAdapter.notifyItemChanged(viewpage2.currentItem)
                        }
                    }
                }

            }
        }
    }

    fun addData(displayUserBean: DisplayUserBean) {
        if (isEmpty()) {
            mAdapter.data[0] = LiveStateBean(displayUserBean, true)
            mAdapter.notifyItemChanged(0)
        } else {
            mAdapter.addData(LiveStateBean(displayUserBean))
        }
        autoGetData(displayUserBean.base.userId)
    }

    /**
     * 用户状态变更
     */
    fun setUserStateChange(list: List<UserStateMessage>) {
        list.forEach {
            if (it.state.userId == getNextUserId()) { //用户是下一个
                //如果是关播或者在通话中，将其删除
                if (it.state.living == 0 || it.state.calling == 1) {
                    val data = mAdapter.getItemOrNull(currentPosition + 1)
                    data?.let { liveStateBean ->
                        mAdapter.removeAt(currentPosition + 1)
                        autoGetData(liveStateBean.displayUserBean?.base?.userId)
                    }
                }
            }
            val item = mAdapter.getItemOrNull(currentPosition)
            item?.let { lv ->
                lv.displayUserBean?.let { dp ->
                    if (it.state.userId == dp.base.userId) {
                        if (dp.base.living != it.state.living || dp.base.calling != it.state.calling) {
                            if (dp.base.living == AppConst.NO && it.state.living == AppConst.YES) {
                                helperCallBack.getUserLiveState(it.state.userId)
                            }
                            mAdapter.data[currentPosition].displayUserBean = dp.copyState(it)
                            mAdapter.notifyItemChanged(currentPosition)
                        }
                        isChangeNext(mAdapter.getItemOrNull(currentPosition)?.displayUserBean)
                    }
                }

            }

        }
    }

    private fun isChangeNext(displayUserBean: DisplayUserBean?) {
        if (displayUserBean == null || displayUserBean.base.living == AppConst.YES || isScrolle) {
            return
        }
        if (getNextUserId() != null) {
            if (currentPosition > 0) {
                viewpage2.setCurrentItem(currentPosition + 1, true)
            }
        } else {
            autoGetData(getCurrentUserId())
        }
    }

    /**
     * 自动判断下次是否获取数据
     */
    private fun autoGetData(userid: Long?) {
        if (currentPosition + REARQUANTITY + 1 > mAdapter.data.size) {
            helperCallBack.getNextDataById(userid)
        }
    }

    fun getUserStateIds(): List<Long> {
        return buildList {
            getCurrentUserId()?.also { add(it) }
            getNextUserId()?.also { add(it) }
        }
    }

    fun getCurrentUserId(): Long? {
        return mAdapter.getItemOrNull(currentPosition)?.displayUserBean?.base?.userId
    }

    private fun getNextUserId(): Long? {
        return mAdapter.getItemOrNull(currentPosition + 1)?.displayUserBean?.base?.userId
    }

    fun isEmpty() = mAdapter.data.size == 1 && mAdapter.getItem(0).displayUserBean == null

    interface HelperCallBack {

        fun getFirstData()
        fun getNextDataById(userid: Long?)
        fun getUserLiveState(userid: Long) //获取用户直播信息

        fun OnItemClickListener(view: View, displayUserBean: DisplayUserBean)
    }

    companion object {

        const val PREORDERQUANTITY = 3 //前置数量
        const val REARQUANTITY = 1   //后置数量
    }
}

